package com.lagou.java.handler;

import com.lagou.java.NettyServer;
import com.lagou.java.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/thread")
public class ThreadHandler {

    @RequestMapping("/add/{port}")
    public String addServer(@PathVariable("port") Integer port) {
        if (port == null) {
            return "端口不能为空！";
        }
        String msg = "";
        Thread thread = ServerBootstrap.serverTreads.get(port);
        if (thread == null) {
            return "不支持该端口, 支持的端口有： " +
                    ServerBootstrap.getPort1() + "/"
                    + ServerBootstrap.getPort2();
        }

        if (thread.getState() != Thread.State.TERMINATED) {
            msg = "该端口有服务端在运行";
        } else {
            Thread server = new Thread(() -> {
                ChannelFuture serviceB = NettyServer
                        .startServer(ServerBootstrap.getHost(), port);
//            String data = NettyServer.getData(NettyServer.basePath);
//            System.out.println("===>" + data);
            });
            server.start();
            ServerBootstrap.serverTreads.put(port, server);
//            String node = NettyServer.cacheNodes.get(port);
//            NettyServer.client.delete(NettyServer.basePath + "/" + node);
            msg = "服务已经在" + port + "端口启动";
        }
        return msg;
    }

    @RequestMapping("/remove/{port}")
    public String removeServer(@PathVariable("port") Integer port) {
        if (port == null) {
            return "端口不能为空！";
        }
        String msg = "";
        Thread thread = ServerBootstrap.serverTreads.get(port);
        if (thread == null) {
            return "不支持该端口, 支持的端口有： " +
                    ServerBootstrap.getPort1() + "/"
                    + ServerBootstrap.getPort2();
        }
        if (thread.getState() == Thread.State.TERMINATED) {
            msg = "该端口服务已经停止运行";
        } else {
            ServerBootstrap.serverServices.get(port).channel().close();
            NettyServer.handlers.get(port).closeConnnection();
            thread.stop();
//            ServerBootstrap.serverServices.remove(port);
            NettyServer.client.delete(NettyServer.basePath + "/" + NettyServer.cacheNodes.get(port));
            msg = "运行在端口 " + port + " 的服务已经停止";
        }
        return msg;
    }
}
